/**
 * 品牌专题维护create on 2017/8/22.
 */
var current_mode ='';                                   //添加 ADD 编辑 MOD

$(document).ready(function(){
    $.fn.dataTable.ext.errMode = 'none';
    $('#table_list').on( 'error.dt', function ( e, settings, techNote, message ) {
        $.jBox.error('可能登录已超时，请刷新页面！其他问题，请联系管理员！' , '错误');
        return false;
    } ).DataTable({
        dom: '<"top">rt<"bottom"flip><"clear">',
        language: {
            "sUrl":'/static/plugins/datatables/language.json'
        },
        "searching": false,
        "processing": true,
        "serverSide": true,
        ajax:{
            url:'/goods-brand/get-detail-list',
            type:'post',
            data:function(d){
                d.search_brand_id = $('#search_brand_id').val();
                d.search_typ = $('#search_typ').val();
            },
            error:getError
        },
        aoColumns: [
            { "data": "", "bSortable": false},
            { "data": "id", "bSortable": true},
            { "data": "typ", "bSortable":false },
            { "data": "img", "bSortable":false },
            { "data": "img_link", "bSortable":false },
            { "data": "img_alt", "bSortable":false },
            { "data": "brand_desc", "bSortable":false },
            { "data": "sort", "bSortable":true },
            { "data": "use_flg", "bSortable":false }
        ],
        columnDefs: [
            {
                "targets": [0],
                "render": function(data, type, full) {
                    return '<a href="javascript:" onclick="updateDetail('+ full.id +')">修改</a>';
                }
            },
            {
                "targets": [2],
                "render": function(data, type, full) {
                    var retStr ='';
                    if(data == 1){
                        retStr = 'PC';
                    }else{
                        retStr = 'WAP';
                    }
                    return retStr;
                }
            },
            {//显示图片
                "targets": [3],
                "render": function(data, type, full) {
                    if(!data == '')
                    {
                        return '<a href="javascript:" onclick="showMoreImg(\''+ data + '\')">' + data + '</a>';
                    }else{
                        return '';
                    }
                }
            },
            {//图片LINK
                "targets": [4],
                "render": function(data, type, full) {
                    if(!data == '')
                    {
                        return '<a href="' + data + '" target = "_blank">点击查看</a>';
                    }else{
                        return '';
                    }
                }
            },
            {
                "targets": [8],
                "data": "use_flg",
                "render": function(data, type, full) {
//                    var  title = '';
//                    if(data == 1){
//                        title = '禁用';
//                    }else{
//                        title = '启用';
//                    }
//                    return '<a href="javascript:" onclick="usflgClick('+ full.id +','+ data + ')">' + title + '</a>';
                    return '<span class="switch" data-id="'+ full.id +'" data-flg="'+(data)+'"><input  style="width:20px;height:20px;" type="checkbox" '+(data == 1 ? 'checked="checked"' : '')+' class="input-check"></span>';
                }
            }
        ],
        order: [[ 1, "desc" ]]                      //初始指定排序字段
    });
});

//查看品牌专题图片
$('.show-img-btn-brand').click(function(){
    var img_url = $(this).attr('data-img');
    showMoreImg(img_url);
});

//品牌图片上传按钮事件
$('.upload-img-btn-brand').click(function(){
    $('.upload_file_ot').trigger('click');
});

//图片选择
$('.upload_file_ot').change(function(){
    if(this.value == ''){
    }else{
        //图片提交
        $('#upload_form_update').submit();
    }
});

//提交品牌数据(添加/编辑)
$('.ajax_submit').click(function(){

    //校验输入项
    if(!checkInput()){
        return;
    }

    $.post($('#group_form').attr('action'),$('#group_form').serialize(),success,'json');
    return false;
    function success(data){
        $.jBox.close();
        $('#myModal').modal('hide');
        if(data.code == 200)
        {
            $.jBox.tip('处理成功', 'success');
            window.setTimeout(function () { reload(); }, 1000);
        }
        else{
            $.jBox.error(data.val, '错误');
        }
    }
});

/**
 * 校验输入项
 * @returns {boolean}
 */
function checkInput(){

    if(  $('#img_url_brand').val() == ''){
        $.jBox.error('请选择图片', '错误');
        return false;
    }
    return true;
}

/**
 * 图片上传动作
 **/
$('#upload_form_update').submit(function(e){
    e.preventDefault();
    $(this).ajaxSubmit({
        beforeSend:function(){
            $('.upload-img-btn-brand').attr('disabled',true);
        },
        success:function(data){
            var result = $.parseJSON(data);
            if(result.code == 500){
                $.jBox.error(result.val, '错误');
            }else{
                $('.show-img-btn-brand').attr('data-img','');
                $('.show-img-btn-brand').hide();
                $('.upload-img-btn-brand').attr('disabled',false);
                $('.show-img-btn-brand').attr('data-img',result.val);
                $('#img_url_brand').val(result.val);
                $('.show-img-btn-brand').show();
            }
        }
    });
});


//查询处理
$('#select_button').click(function(){
    var table = $('#table_list').DataTable();
    table.ajax.reload();
})

/**
 * 显示图片
 **/
function showMoreImg(objKey){
    if(objKey == '' || objKey == null || objKey == undefined){
        $.jBox.error('数据为空', '错误');
        return;
    }

    var json = {
        "title": "图片", //相册标题
        "id": 0, //相册id
        "start": 0, //初始显示的图片序号，默认0
        "data": [   //相册包含的图片，数组格式
            {
                "alt": "",//图片名
                "pid": 0, //图片id
                "src": $('#imageBathUrl').val()  + objKey, //原图地址
                "thumb": "" //缩略图地址
            }
        ]
    };
    layer.photos({
        photos: json
    });
}
//编辑专题图片
function updateDetail(id){
    current_mode = 'MOD';                                               //当前为查看模式
    $('#current_mode').val(current_mode);
    resetValue();
    loadDetailData(id);
}

//加载数据
function loadDetailData(id){
    $.ajax({
        type: "post",
        dataType: "json",
        url:'/goods-brand/get-detail-view',
        data: {id:id},
        success: function (data) {
            if(data.code == 200)
            {
                setValue(data);                                          //设置内容
                $('#myModal').modal('show');
            }
            else{
                $.jBox.error(data.val, '错误');
            }
        }
    });
}
//设置控件内容
function setValue(data){
    if(current_mode == 'ADD'){
        $('.ajax_submit').show();                          //隐藏提交按钮
        return;
    }
    var detail_data = JSON.parse(data.val);                  //后端JSON字符串转JSON对像
    $("#brand_id").val(detail_data['brand_id']);          //品牌ID
    $("#brand_name").val(detail_data['brand_name']);     //品牌名称
    $("#brand_desc").val(detail_data['brand_desc']);
    $("#typ").val(detail_data['typ']);
    $("#img_url_brand").val(detail_data['img']);
    $("#img_link").val(detail_data['img_link']);
    $("#img_alt").val(detail_data['img_alt']);
    $("#sort").val(detail_data['sort']);
    $("#use_flg").val(detail_data['use_flg']);
    $("#id").val(detail_data['id']);

    if(detail_data['img'] != ''){
        $('.show-img-btn-brand').attr('data-img',detail_data['img']);
        $('#img_url_brand').val(detail_data['img']);
        $('.show-img-btn-brand').show();
    }

}

//重置操作
$('#reset_button').click(function(){
    $('#search_typ').val('');
    reload();
});

//后退操作
$('#back_button').click(function(){
    history.back();
});

//重新加载数据
function reload(){
    var table = $('#table_list').DataTable();
    table.ajax.reload();
}

//添加品牌图片
$('#add_button').click(function(){
    current_mode = 'ADD';
    $('#current_mode').val(current_mode);
    resetValue();                                   //重置控件
    setValue();
    $('#myModal').modal('show');
});

/**
 * 重置编辑层数据
 */
function resetValue(){

    if(current_mode == 'ADD'){
        $('#myModalLabel').html('添加品牌专题图片');
        $('.ajax_submit').show();                          //显示提交按钮
    }

    if(current_mode == 'MOD'){
        $('#myModalLabel').html('编辑品牌专题图片');
        $('.ajax_submit').show();                          //显示提交按钮
    }

    $("#typ").val('1');
    $("#img_url_brand").val('');
    $("#img_link").val('');
    $("#img_alt").val('');
    $("#brand_desc").val('');
    $("#sort").val('0');
    $('.show-img-btn-brand').attr('data-img','');
    $('.show-img-btn-brand').hide();
}

/**
 * 启用/禁用
 * @param id
 * @param useFlg
 */
function usflgClick(id , useFlg){
    var title = '';
    //var useFlg = 0;
    postUrl = '/goods-brand/change-detail-useflg';

    if(useFlg == 1){
        title = '确定禁用吗？';
        useFlg = 0;
    }else{
        title = '确定启用吗？';
        useFlg = 1;
    }

    $.jBox.confirm(title, "提示", function(v){
        if (v == 'ok'){
            $.post(postUrl,{id:id,useFlg:useFlg},success,'json');
            return false;
            function success(data){
                $.jBox.close();                             //关闭对话框
                if(data.code == 200)
                {
                    $.jBox.tip('处理成功', 'success');
                    window.setTimeout(function () { reload(); }, 1000);
                }
                else{
                    $.jBox.error(data.val, '错误');
                }
            }
        }else{
        	if(useFlg == 1){
        		$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',false);
        	}else{
        		$('#table_list').find('span[data-id='+id+']').children('input').prop('checked',true);
        	}
            $.jBox.close();
        }
    });
}

$('table').on('click','.input-check',function(){
	var id = $(this).parent().attr('data-id');
	var use_flg = $(this).parent().attr('data-flg');
	usflgClick(id,use_flg);
});